package com.oocl.consumer;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.jms.JMSException;
import javax.jms.TextMessage;

import org.json.JSONException;
import org.json.JSONObject;

import com.oocl.dao.BooksDao;
import com.oocl.dao.impl.BooksDaoImpl;
import com.oocl.pojo.Books;

public class MessageHandler {
	private BooksDao booksDao;
   public MessageHandler(){
	   booksDao = new BooksDaoImpl();
   }
   
   public void  handlerMessage(TextMessage msg){
	   try {
		String jsonStr = msg.getText();
			JSONObject jsonObj = new JSONObject(jsonStr);
		    Books book = toBook(jsonObj);
		    booksDao.addBook(book);
	} catch (JSONException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (JMSException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
   }

private Books toBook(JSONObject jsonObj) {
	Books book = new Books();
	try {
		book.setAuthor((String)jsonObj.get("author"));
		book.setName((String)jsonObj.get("name"));
		book.setNewBook(Boolean.parseBoolean((String)jsonObj.get("newBook")));
		book.setPrice(Double.parseDouble((String)jsonObj.get("price")));
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date date = df.parse((String)jsonObj.get("pubDate"));
		book.setPubDate(date);
		book.setPublisher((String)jsonObj.get("publisher"));
	}  catch (ParseException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}catch (JSONException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return book;
}
   
}
